package org.zn.note.spring.client;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.zn.note.spring.domain.Ingredient;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class RestTemplateExample {

    private static final RestTemplate rest = new RestTemplate();
    private static final String ingredientsUrl = "http://localhost:8080/ingredients/{id}";

    // GET 请求
    private Ingredient getIngredientById(String ingredientId) {

        // 方式一：接收String作为参数
        Ingredient result = rest.getForObject(
                ingredientsUrl,
                Ingredient.class, // 返回的Object类型
                ingredientId); // Object... uriVariables，用于替换url中的占位符
        /*
        等价于
        execute(ingredientsUrl,
            HttpMethod.GET, // GET 请求
            requestCallback,  // new AcceptHeaderRequestCallback(responseType = Ingredient.class)
            responseExtractor,
            uriVariables);
         */

        // 方式二：接收Map作为参数
        Map<String, String> urlVariables = new HashMap();
        urlVariables.put("id", ingredientId);
        result = rest.getForObject(ingredientsUrl, Ingredient.class, urlVariables); // 相比如上面按顺序替换，这里是按变量名替换

        // 方式三：构造url
        URI uri = UriComponentsBuilder.fromHttpUrl(ingredientsUrl).build(urlVariables);
        result = rest.getForObject(uri, Ingredient.class);

        // 上面仅仅是返回领域对象，如果想要更多细节(比如报文头)，就需要ResponseEntity
        ResponseEntity<Ingredient> responseEntity = rest.getForEntity(ingredientsUrl, Ingredient.class, ingredientId);
        HttpHeaders headers = responseEntity.getHeaders(); // response header
        result = responseEntity.getBody(); // 领域对象(用response body转换来的)

        return result;
    }

    // HTTP PUT
    private void updateIngredient(Ingredient ingredient) {
        rest.put(ingredientsUrl, ingredient, ingredient.getId());
    }

    // HTTP DELETE
    private void deleteIngredient(Ingredient ingredient) {
        rest.delete(ingredientsUrl, ingredient.getId());
    }

    // HTTP POST
    private Ingredient createIngredient(Ingredient ingredient) {
        String url = "http://localhost:8080/ingredients";
        // 返回资源的domain
        Ingredient result = rest.postForObject(
                url,
                ingredient,
                Ingredient.class
        );
        // 返回资源的URI（新建资源），是从Response Header Location获取的
        URI uri = rest.postForLocation(url, ingredient);
        // 返回Response信息
        ResponseEntity<Ingredient> responseEntity = rest.postForEntity(url, ingredient, Ingredient.class);
        uri = responseEntity.getHeaders().getLocation(); // 等效于上面
        result = responseEntity.getBody();

        return result;
    }
}
